#include "LivingEntity.h"

#include <iostream>

LivingEntity::LivingEntity()
{
    x = 0;
    y = 0;
    motionX = 0;
    motionY = 0;
    invulnerabilityFrames = 0;

    data = new LivingEntityData;
    data->mass = 0;
    data->speed = 0;
    static_cast<LivingEntityData*>(data)->hp = 0;
    static_cast<LivingEntityData*>(data)->dmg = 0;

    needsRemoval = false;
}

void LivingEntity::tick()
{
    Entity::tick();

    if(invulnerabilityFrames)
        invulnerabilityFrames--;
}

void LivingEntity::updateSprite()
{
    Entity::updateSprite();
    sf::Color c = invulnerabilityFrames ? sf::Color(255,100,100,180) : sf::Color(255,255,255,255);
    sprite.setColor(c);
}

void LivingEntity::onCollide(Entity* e)
{
    if(static_cast<LivingEntityData*>(data)->dmg)
        e->takeHit(static_cast<LivingEntityData*>(data)->dmg, this);
}

void LivingEntity::takeHit(int dmg, Entity* e)
{
    if(!invulnerabilityFrames)
    {
        hp -= dmg;
        if(hp < 0)
            hp = 0;
        motionX = (x < e->getX() ? -0.1f : 0.1f);
        motionY = 0.1f;
        invulnerabilityFrames = timeInvulnerable();
    }
}

void LivingEntity::heal(int i)
{
    if(isAlive())
    {
        hp += i;
        if(hp > getMaxHP())
            hp = getMaxHP();

        if(hp < 0)
            hp = 0;
    }
}

int LivingEntity::timeInvulnerable()
{
    return 40;
}

bool LivingEntity::isAlive()
{
    return hp > 0;
}

int LivingEntity::getMaxHP()
{
    return static_cast<LivingEntityData*>(data)->hp;
}

LivingEntity* LivingEntity::setMaxHP(int i)
{
    static_cast<LivingEntityData*>(data)->hp = i;
    return this;
}

LivingEntity* LivingEntity::setDamages(int i)
{
    static_cast<LivingEntityData*>(data)->dmg = i;
    return this;
}


Entity * LivingEntity::clone()
{
    return new LivingEntity(*this);
}
